<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='name' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #rules='{record}'>
            <template v-for="(rule, i) in record.rules">
                <div>{{ rule.time[0] }} - {{ rule.time[1] }} 电价{{ rule.price }}元/度 服务费{{ rule.service }}元/度</div>
            </template>
        </template>
    </BPTable>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='900px' :confirm='submit' @close='close'>
        <a-form ref='formRef' :model='formData' :label-col="{ span: 2 }">
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item :label="$t('name')" name='name' label-align="left" :rules="[{required : true}]">
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.name' />
            </a-form-item>
            <a-form-item label="预付费" name='pay' label-align="left" :rules="[{required : true}]">
                <a-input :min="0" type='number' v-model:value.number='formData.pay'>
                    <template #addonAfter>元</template>
                </a-input>
            </a-form-item>

            <a-form-item :label-col='{span : 24}' required :wrapper-col="{ offset: 1}">
                <template #label>标准：</template>
                <template v-for="(rule, i) in formData.rules" :key="i">
                    <a-space :size="30" :style="{marginTop : i == 0 ? '0' : '20px'}">
                        <a-form-item :class="$style.ruleItem" label="开始" :name="['rules', i, 'time', 0]" :rules="[{required : true,}]">
                            <a-select style="width: 90px;" v-model:value="rule.time[0]">
                                <a-select-option v-for="(time, i) in times" :key="i" :value="time">{{ time }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item :class="$style.ruleItem" label="结束" :name="['rules', i, 'time', 1]" :rules="[{required : true,}]">
                            <a-select style="width: 90px;" v-model:value="rule.time[1]">
                                <a-select-option v-for="(time, i) in times" :key="i" :value="time">{{ time }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item :class="$style.ruleItem" label="电价" :name="['rules', i, 'price']" :rules="[{required : true}]">
                            <a-input style="width: 130px;" :maxlength='30' type='number' :min="0" v-model:value.number='rule.price'>
                                <template #addonAfter>元/度</template>
                            </a-input>
                        </a-form-item>
                        <a-form-item :class="$style.ruleItem" label="服务费" :name="['rules', i, 'service']" :rules="[{required : true,}]">
                            <a-input style="width: 130px;" :maxlength='30' type='number' :min="0" v-model:value.number='rule.service'>
                                <template #addonAfter>元/度</template>
                            </a-input>
                        </a-form-item>
                        <MinusCircleOutlined @click="delRule(i)" />
                    </a-space>
                </template>
            </a-form-item>
            <a-form-item :wrapper-col='{offset : 1}'>
                <a-button type="dashed" @click="addRule"><PlusOutlined />{{ $c('add') }}</a-button>
            </a-form-item>
        </a-form>
    </BDialog>
</template>

<script lang='ts' setup>
    import { computed, nextTick, ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';

    
    import { pageApi, saveApi, deleteApi } from "@/api/pricingRule/Fast";
    import { parseTime } from "@/utils";
    import { useResourceStore } from "@/store/resource";
    import { useI18nStore } from "@/store/i18n";
import { optionOptions } from "ant-design-vue/es/vc-mentions/src/Option";

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const tableRef = ref()

    const times:string[] = []
    for(let i = 0; i <= 24; i ++) {
        const h = String(i).padStart(2, '0')
        times.push(h + ':00')
        if(i < 24) {
            times.push(h + ':30')
        }
    }

    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission('pricing:add')) {
        buttons.value.push({
            button : 'add',
            func : () => {
                
                dialogTitle.value = i18n.t('add')
                visible.value = true
            }
        })
    }


    
    const formData = ref<any>({
        id : 0,
        name : '',
        pay : '',
        rules : []
    })


    function addRule() {
        formData.value.rules.push({price : '', service : '', time : ['', '']})
    }

    addRule()

    function delRule(i:number) {
        Modal.confirm({
            title : i18n.t('confirmDel', ['']),
            onOk() {
                formData.value.rules.splice(i, 1)
            }
        })
    }


    //关闭的时候清空表单
    function close() {
        formRef.value.resetFields()
        formRef.value.clearValidate()
    }

    

    async function submit() {
        let params  = await formRef.value.validate()
        
        const res = await saveApi(params)
        if(res.success) {
            tableRef.value.reload()
            message.success(i18n.t('saveSuccess'))
            close()
            visible.value = false
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }




    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : i18n.t('name'),
            inSearch : true,
        },

        {
            dataIndex : 'pay',
            title : '预付金额（元）',
        },

        {
            dataIndex : 'rules',
            title : '明细',
        },

        {
            title : i18n.t('updateTime'),
            dataIndex : 'updateTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },

        {
            title : i18n.t('createTime'),
            dataIndex : 'createTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },
        
        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit : resourceStore.hasPermission('pricing:update') ? (row) => {
                dialogTitle.value = i18n.t('edit')
                visible.value = true
                nextTick(() => {
                    for(let k in formData.value) {
                        if(k in row) {
                            formData.value[k] = row[k]
                        }
                        
                    }
                })
            } : undefined,

            $delete : resourceStore.hasPermission('pricing:delete') ? async(row, index) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    tableRef.value.reload()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            } : undefined
            
        },
    ])



</script>

<style lang="scss" module>
    .ruleRow{
        display: flex;
        align-items: center;

        .input{
            flex: 1;
        }
        .minus{
            margin-left: 10px;
            color: #999;
            cursor: pointer;
            font-size: 24px;
        }
    }

    .ruleItem{
        margin-bottom: 0 !important;
    }
</style>